package service

import (
	"fmt"
	"io"
	"math/rand"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

type UploadService interface {
	UploadImage(file multipart.File, header *multipart.FileHeader) (string, error)
}
type UploadServiceImpl struct {
	uploadDir string
}

func NewUploadService(uploadDir string) UploadService {
	_ = os.MkdirAll(uploadDir, os.ModePerm)
	return &UploadServiceImpl{
		uploadDir: uploadDir,
	}
}
func (s *UploadServiceImpl) UploadImage(file multipart.File, header *multipart.FileHeader) (string, error) {
	// MIME 类型检查
	buffer := make([]byte, 512)
	_, err := file.Read(buffer)
	if err != nil {
		return "", fmt.Errorf("读取文件失败: %v", err)
	}
	_, _ = file.Seek(0, io.SeekStart)

	contentType := http.DetectContentType(buffer)
	if !strings.HasPrefix(contentType, "image/") {
		return "", fmt.Errorf("上传文件不是图片")
	}

	// 文件后缀提取
	suffix := filepath.Ext(header.Filename)
	if suffix == "" {
		suffix = ".png"
	}

	// 生成安全文件名
	fileName := fmt.Sprintf("%d_%08d%s", time.Now().UnixNano(), rand.Int31(), suffix)

	// 构建路径并保存
	dstPath := filepath.Join(s.uploadDir, fileName)

	dst, err := os.Create(dstPath)
	if err != nil {
		return "", fmt.Errorf("创建目标文件失败: %v", err)
	}
	defer dst.Close()

	_, err = io.Copy(dst, file)
	if err != nil {
		return "", fmt.Errorf("文件拷贝失败: %v", err)
	}

	// 返回访问路径
	return "/asset/upload/" + fileName, nil
}
